import { Button, Form, Modal, Spin } from 'antd';
import {
  WeaDialog,
  WeaTableEdit,
  WeaCheckbox,
  WeaInput,
  WeaFormItem,
  WeaError,
  WeaColorPicker,
  WeaLocaleProvider,
} from 'ecCom';
import CoworkConstant from '../../../util/CoworkConstant';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';

const getLabel = WeaLocaleProvider.getLabel;

class TagForm extends React.Component {
  constructor(props) {
    super(props);
    this.initColor = '#6aa84f';
    this.state = {
      datas: props.datas,
      checkAll: props.datas.every(data => data.isUsed == 1),
      colorIdx: -1,
      color: this.initColor,
      selectRowKeys: [],
    };
  }

  componentDidMount() {
    this.props.initFunc && this.props.initFunc(this);
  }
  onRowSelect = keys => this.setState({ selectRowKeys: keys });

  render() {
    let { datas, colorIdx, color, selectRowKeys } = this.state;
    let { height } = this.props;
    return (
      <Form
        ecId={`${(this && this.props && this.props.ecId) || ''}_Form@2mqmkd`}
        inline
      >
        <WeaTableEdit
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTableEdit@4ap9nu`}
          columns={this.getFormColumns(this.props.form)}
          datas={datas}
          title={getLabel(382640, '协作标签')}
          onChange={this.onChange}
          selectedRowKeys={selectRowKeys}
          addPosition="first"
          getRowSelection={this.getRowSelection}
          onRowSelect={this.onRowSelect}
          tableProps={{ scroll: { y: height - 91 } }}
          copyFilterProps={['id']}
        />
        <WeaDialog
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaDialog@rweh5z`}
          visible={colorIdx != -1}
          title={`${getLabel(31214, '标签颜色')}${getLabel(130599, '设置')}`}
          icon={CoworkConstant.iconClassName}
          iconBgcolor={CoworkConstant.iconBgColor}
          style={{ width: 300, height: 87 }}
          onCancel={this.backColor}
          buttons={[
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@0rnxv5@save`}
              type="primary"
              onClick={this.saveColor}
            >
              {getLabel(86, '保存')}
            </Button>,
          ]}
        >
          <div className="wea-cowrk-tagset">
            <WeaColorPicker
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaColorPicker@9oav4o`}
              onChange={this.changeColor}
              value={color}
            />
          </div>
        </WeaDialog>
      </Form>
    );
  }

  getTagColor = (text, record, index) => {
    if (record.labelType == 'typePlate') {
      return null;
    }
    let color = text && text != 'null' ? text : this.initColor;
    return (
      <span
        style={{ backgroundColor: color, color: '#fff' }}
        className="tag-color"
        onClick={() => this.openColor(index, color)}
      >
        {color}
      </span>
    );
  };

  getFormColumns = (form) => {
    const { getFieldProps } = form;
    let tagColumns = [
      {
        title: getLabel(81323, '标签名称'),
        dataIndex: 'labelName',
        key: 'labelName',
        width: '30%',
        render: (text, record, index) => {
          let colProps = getFieldProps(`labelArray[${index}].labelName`, {
            initialValue: text,
            onChange: this.changeName.bind(this, index),
          });
          if (record.labelType == 'typePlate') {
            colProps.viewAttr = 1;
          } else {
            colProps.viewAttr = 3;
          }
          return (
            <WeaFormItem
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaFormItem@pa5siy@${index}`}
            >
              <WeaError
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaError@y5gk8p@${index}`}
                tipPosition="bottom"
                ref="weaError"
                error={getLabel('513144', '标签名称为必填')}
              >
                <WeaInput
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaInput@casdnh@${index}`}
                  {...colProps}
                  value={text}
                />
              </WeaError>
            </WeaFormItem>
          );
        },
      },
      {
        title: getLabel(31214, '标签颜色'),
        dataIndex: 'labelColor',
        key: 'labelColor',
        width: '30%',
        render: this.getTagColor,
      },
      {
        title: (
          <div>
            <WeaCheckbox
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaCheckbox@mwwjfq@checkAll`}
              onChange={this.checkAll}
              value={this.state.checkAll}
            />
            <span className="ml5">{getLabel(382641, 'TAB标签显示')}</span>
          </div>
        ),
        dataIndex: 'isUsed',
        key: 'isUsed',
        width: '40%',
        render: (text, record, index) => {
          let colProps = getFieldProps(`labelArray[${index}].isUsed`, {
            initialValue: text == 1,
          });
          return (
            <div>
              <WeaCheckbox
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaCheckbox@bo7gts@checkOne`}
                {...colProps}
                value={text}
                onChange={this.checkOne.bind(this, index)}
              />
            </div>
          );
        },
      },
    ];
    return tagColumns;
  };

  validateFieldsAndScroll = () => {
    let { datas = [] } = this.state;
    let saveParams = {};
    let canSave = true;
    // 名称必填校验
    datas.map((v) => {
      if (!v.labelName || v.labelName.split(' ').join('').length == 0) {
        canSave = false;
      }
    });
    if (!canSave) {
      Modal.error({
        title: getLabel(15172, '系统提示'),
        content: getLabel('513144', '标签名称为必填'),
      });
    } else {
      // 处理数据：这里的数据经常有问题，要处理下
      saveParams = datas.map((data) => {
        let param = { ...data };
        if (!param.id && !param.labelType) {
          param.labelType = 'label';
          if (!param.labelColor) {
            param.labelColor = this.initColor;
          }
        }
        param.isUsed = param.isUsed == true || param.isUsed == 1 ? 1 : 0;
        return param;
      });
    }
    return {
      canSave,
      params: saveParams,
    };
  };

  onChange = (datas) => {
    let checkAll = datas.every(data => data.isUsed == 1);
    this.setState({
      datas,
      checkAll,
    });
  };

  checkAll = (bool) => {
    let datas = this.state.datas.map(data => ({ ...data, isUsed: bool }));
    this.setState({
      datas,
      checkAll: bool,
    });
  };

  checkOne = (index, bool) => {
    let data = { ...this.state.datas[index] };
    data.isUsed = bool;
    let datas = [...this.state.datas];
    datas[index] = data;
    this.onChange(datas);
  };

  openColor = (index, color) => {
    this.setState({
      colorIdx: index,
      color,
    });
  };
  saveColor = () => {
    let data = { ...this.state.datas[this.state.colorIdx] };
    data.labelColor = this.state.color;
    let datas = [...this.state.datas];
    datas[this.state.colorIdx] = data;
    this.setState({
      datas,
    });
    this.backColor();
  };
  backColor = () => {
    this.setState({
      colorIdx: -1,
      color: '#d9d9d9',
    });
  };
  changeColor = (color) => {
    this.setState({
      color,
    });
  };
  reset = () => {
    this.setState({
      datas: this.props.datas,
      selectRowKeys: [],
    });
    this.props.form.setFieldsValue({ labelArray: this.props.datas });
  };

  getRowSelection = (rowSelection) => {
    let sel = { ...rowSelection };
    sel.getCheckboxProps = record => ({
      disabled: record.labelType == 'typePlate',
    });
    return sel;
  };
  changeName = (index, value) => {
    let datas = [...this.state.datas];
    datas[index] = { ...datas[index], labelName: value };
    this.setState({ datas });
  };
}
/* eslint-disable */
TagForm = Form.create()(TagForm);
/* eslint-enable */

@inject('coworkMainStore')
@observer
class CoworkTagDialog extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      height: 600,
    };
  }

  render() {
    let { height } = this.state;
    const { coworkMainStore } = this.props;
    const { config, tagLoading } = coworkMainStore;
    const { labelList, tagVisible } = toJS(config);
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@v1mow6`}
        className="wea-cowork-tag"
        visible={tagVisible}
        title={`${getLabel(31214, '标签颜色')}${getLabel(130599, '设置')}`}
        icon={CoworkConstant.iconClassName}
        iconBgcolor={CoworkConstant.iconBgColor}
        style={{ width: 800, height: 600 }}
        onCancel={this.back}
        onChangeHeight={this.changeHeight}
        buttons={[
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@zrsfvu@save`}
            type="primary"
            onClick={this.submit}
          >
            {getLabel(86, '保存')}
          </Button>,
        ]}
      >
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@ioxzzg`}
          spinning={tagLoading}
        >
          <div className="wea-cowork-dialog tag-table-div">
            <TagForm
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_TagForm@skdcjq`}
              initFunc={form => (this.form = form)}
              datas={labelList}
              height={height}
            />
          </div>
        </Spin>
      </WeaDialog>
    );
  }

  open = () => {
    const { coworkMainStore } = this.props;
    coworkMainStore.setTagVisible(true);
  };

  back = () => {
    const { coworkMainStore } = this.props;
    const { content } = coworkMainStore;
    coworkMainStore.setTagVisible(false);
    coworkMainStore.reloadLeftList();
    if (content && content.id) coworkMainStore.reloadCowork();
    this.form.reset();
  };

  submit = () => {
    const { coworkMainStore } = this.props;

    let res = this.form.validateFieldsAndScroll(); // 做校验，改数据
    if (res.canSave) {
      const values = res.params;
      let params = {
        labelArray:
          Object.keys(values).length !== 0
            ? JSON.stringify(values)
            : JSON.stringify([]),
      };
      coworkMainStore.uploadCoworkLabelList(params, () => {
        coworkMainStore.getCoworkLabelList(this.back);
      });
    }
  };

  changeHeight = (height) => {
    this.setState({ height });
  };
}

export default CoworkTagDialog;
